/**
 * user apis
 */
import { user, factory } from '../models'
import { Router } from 'express'
import { assign, isEmpty } from 'lodash'
import uuid from 'node-uuid'

let routes = Router()

/**
 * user registe
 * @param  {[type]} '/'   [description]
 * @param  {[type]} (req, res           [description]
 * @return {[type]}       [description]
 */
routes.post('/modify', (req, res) => {
  user.upsert(req.body).then(() => res.json({}))
})

/**
 * user login
 * @param  {[type]} '/login' [description]
 * @param  {[type]} (req,    res           [description]
 * @return {[type]}          [description]
 */
routes.post('/login', (req, res) => {
  var params = assign({}, req.body)
  var result = {
    access: false
  }
  user.findOne({
    where: params,
    raw: true
  }).then(data => {
    if (data) {
      var sess = req.session
      sess.logined = true
      sess.user = data
      result.user = data
      return factory.findOne({
        where: {
          user_id: data.id
        },
        raw: true
      })
    } else {
      throw new Error()
    }
  }).then(factory => {
    result.factory = factory
    result.access = true
    res.json(result)
  }).catch(data => res.json({
    access: false
  }))
})

/**
 * user login
 * @param  {[type]} '/login' [description]
 * @param  {[type]} (req,    res           [description]
 * @return {[type]}          [description]
 */
routes.post('/register', (req, res) => {
  let userInfo = assign({
    id: uuid.v4()
  }, req.body.user)
  let factoryInfo = assign({
    id: uuid.v4(),
    user_id: userInfo.id
  }, req.body.factory)
  user.upsert(userInfo).then(data => {
    return factory.upsert(factoryInfo)
  }).then(() => {
    res.json({
      code: '00',
      message: 'success'
    })
  })

})

export default routes
